package edu.ahut.corejava3;

import javafx.util.Pair;

import java.util.*;

//统计一句话中每一个单词出现的次数，并按照出现次数从多到少排序，相同的次数用字典排序
public class Exp04WordsCounter2 {
    public static void main(String[] args) {
        String line = "To  know  everything is to know   nothing.";
        Map<String, Integer> map = new TreeMap<String, Integer>();
        System.out.println(line = line.toLowerCase().replaceAll("[^a-zA-z]", " ").trim());
        System.out.println(line);//
        String[] words = line.split("\\s+");
        System.out.println(Arrays.toString(words));
        for (String word : words) {
            if (map.containsKey(word)) {
                int old = map.get(word);
                map.put(word, old + 1);
            } else {
                map.put(word, 1);
            }
        }
        System.out.println(map);
        Queue<Pair<String, Integer>> q = new PriorityQueue<>(
                new Comparator<Pair<String, Integer>>() {
                    @Override
                    public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) {
                        if (!o1.getValue().equals(o2.getValue())) {
                            return o2.getValue() - o1.getValue();
                        }
                        return o1.getKey().compareTo(o2.getKey());
                    }
                }
        );
        for (String word : map.keySet()) {
            q.offer(new Pair<>(word, map.get(word)));
        }
        for (int i = 0; i < 10 && !q.isEmpty(); i++) {
            System.out.println(q.peek().getKey() + "-----" + q.peek().getValue());
            q.poll();
        }


    }
}
